<?php
namespace app\api\controller;
use app\admin\model\Admin;
use app\admin\model\detection\Orders;
use app\admin\model\disassemble\Order;
use app\admin\model\Withdrawal;
use app\common\controller\AdminApi;
use app\common\library\Sms;
use app\common\model\User;
use think\App;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
class Store extends AdminApi
{
    //登录
    public function authLogin()
    {
        $this->login();
    }
    //资料
    public function authProfile()
    {
        $this->profile();
    }
    //关于我们
    public function aboutUs()
    {
        $this->success('关于我们',Config("site.storeAboutUs"));
    }
    //重置密码
    public function resetpwd()
    {
        $this->requireAdminLogin();

        $mobile = $this->request->post("mobile");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $user = Admin::getByMobile($mobile);
        if (!$user) {
            $this->error(__('User not found'));
        }
        $ret = Sms::check($mobile, $captcha, 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($mobile, 'resetpwd');

        //密码修改
        $user->password = $this->getEncryptPassword($newpassword, $user->salt);
        $ret = $user->save();
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error('Network error');
        }
    }
    /**
     * @return void
     * 用户钱包
     */
    public function moneyInfo()
    {
        $this->requireAdminLogin();
        $data['money'] = db('user_money_log')->where(['user_id'=>$this->admin->userid])->sum('money');
        $data['not_money'] = Order::where(['userid'=>$this->admin->userid,'status'=>['neq',4]])->sum('end_price');
        $this->success($this->successMsg,$data);
    }
    /**
     * @return void
     * @throws \think\exception\DbException
     * 钱包明细
     */
    public function moneyList()
    {
        $this->requireAdminLogin();
        $type = request()->post('type',0);
        $data = [];
        if($type == 1)
        {
            //提现
            $model = new Withdrawal();
            $data = $model->where(['userid'=>$this->admin->userid])->order('id desc')->paginate();
        }else{
            //收入
            $data = db('user_money_log')->where(['user_id'=>$this->admin->userid,'money'=>['>',0],'memo'=>['neq','提现驳回返回钱包']])->order('id','desc')->paginate();
        }
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * get获取银行账户信息，post提交提现
     */
    public function walletOut()
    {
        $this->requireAdminLogin();
        if($this->request->isPost())
        {
            //发起提现
            $params = $this->request->post();
            if(!isset($params['amount']) || $params['amount'] <= 0)
                $this->error($this->warningMsg = '请正确填写提现金额');
            if($params['amount'] < 100)
                $this->error($this->warningMsg = '最低提现金额100元');
            if(!isset($params['bank_name']) || $params['bank_name'] == '' || !isset($params['bank_card_number']) || $params['bank_card_number'] == '')
                $this->error($this->warningMsg = '请输入银行账户信息');
            $params['userid'] = $this->admin->userid;
            $params['createtime'] = time();
            $res = db('user_withdrawal')->insert($params);
            if(!$res)
                $this->error($this->errorMsg);
            //开始扣除余额

            \app\common\model\User::money(-$params['amount'],$params['userid'],'提现扣除');
            $this->success($this->successMsg);
        }
        //获取上次提现的银行卡信息
        $data = db('user_withdrawal')->where(['userid'=>$this->admin->userid])->order('id','desc')->field('bank_name,bank_card_number')->find();
        $this->success($this->successMsg,$data);
    }
    //小程序首页
    public function homeIndex()
    {
        $this->requireAdminLogin();
        $user = \app\common\model\User::get($this->admin->userid);
        //开始进行数据整理
        $param = $this->request->post();
        $data['allMoney'] = $user->money;//总收入
        //总应付，需要查找所有未付款的回收订单
        $model = new Order();
        $data['payment'] = $model->where(['end_adminid'=>$this->admin->id,'end_status'=>0])->sum('end_price');//回收应付
        $data['overed'] = $model->where(['end_adminid'=>$this->admin->id,'overtype'=>1])->count();//已注销车辆
        $data['normal'] = $model->where(['end_adminid'=>$this->admin->id,'overtype'=>0])->count();//未注销车辆
        //检测订单model初始化
        $check = new Orders();
        $param['type'] = $param['type'] ?? 0;
        switch($param['dateType'])
        {
            case 0:
                //本日
                $param['begin'] = strtotime("today");
                $param['end'] = strtotime("tomorrow") - 1;
                break;
            case 1:
                //本周
                $param['begin'] = strtotime("Monday this week");
                $param['end'] = strtotime("Sunday this week") + 86399;
                break;
            case 2:
                //本月
                $month_time = month_time(date('Y-m'));
                $param['begin'] = $month_time['begin'];
                $param['end'] = $month_time['end'];
                break;
            default:
                //自定义
                break;
        }
        //进行数据判定
        switch ($param['type']) {
            case 0:
                //已预约订单
                $where = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3]]];
                $whereOne = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3]]];
                $whereTwo = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3]]];
                break;
            case 1:
                //已完成订单
                $where = ['end_adminid'=>$this->admin->id,'overtime'=>['between',[$param['begin'],$param['end']]],'status'=>4];
                $whereOne = ['end_adminid'=>$this->admin->id,'overtime'=>['between',[$param['begin'],$param['end']]],'status'=>4];
                $whereTwo = ['end_adminid'=>$this->admin->id,'overtime'=>['between',[$param['begin'],$param['end']]],'status'=>4];
                break;
            case 2:
                //售后订单
                $warnTime = strtotime("-15 days");
                $where = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3,4]],'createtime'=>['<',$warnTime],'overtype'=>0];
                $whereOne = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3,4]],'type'=>1,'san_check|look_check|low_check|obd_check|huan_check|an_check'=>2];
                $whereTwo = ['end_adminid'=>$this->admin->id,'createtime'=>['between',[$param['begin'],$param['end']]],'status'=>['in',[1,2,3,4]],'type'=>2,'san_check'=>2];
                break;
        }
        $checkMoney = bcadd($check->where($whereOne)->sum('end_price'),$check->where($whereTwo)->sum('end_price'),2);
        $backMoney = $model->where($where)->sum('end_price');
        $checkNum = bcadd($check->where($whereOne)->count(),$check->where($whereTwo)->count(),0);
        $backNum = $model->where($where)->count();
        $checkUser = bcadd($check->where($whereOne)->group('userid')->count(),$check->where($whereTwo)->group('userid')->count(),0);
        $backUser = $model->where($where)->group('userid')->count();
        $checkOne = $check->where($whereOne)->count();//车辆检测
        $checkTwo = $check->where($whereTwo)->count();//三电检测

        //开始数据组装
        $data['orderMoney'] = bcadd($checkMoney,$backMoney,2);
        $data['orderNum'] = bcadd($checkNum,$backNum,0);
        $data['orderUser'] = bcadd($checkUser,$backUser,0);
        $data['orderBack'] = $backNum;
        $data['orderOne'] = $checkOne;
        $data['orderTwo'] = $checkTwo;
        $this->success($this->successMsg,$data);
    }
    //订单首页
    public function orderIndex()
    {
        $this->requireAdminLogin();
        //检测订单model初始化
        $check = new Orders();
        //总应付，需要查找所有未付款的回收订单
        $model = new Order();

        //开始数据组装
        $data['willCheck'] = $check->where(['end_adminid'=>$this->admin->id,'status'=>['in',[1,2,3]]])->count();//已预约检测订单
        $data['willBack'] = $model->where(['end_adminid'=>$this->admin->id,'status'=>['in',[1,2,3]]])->count();//已预约回收订单
        $data['willAll'] = bcadd($data['willCheck'],$data['willBack'],0);//总预约订单

        $data['overCheck'] = $check->where(['end_adminid'=>$this->admin->id,'status'=>4])->count();//已完成检测订单
        $data['overBack'] = $model->where(['end_adminid'=>$this->admin->id,'status'=>4])->count();//已完成回收订单
        $data['overAll'] = bcadd($data['overCheck'],$data['overBack'],0);//总已完成订单

        $data['warnBack'] = $model->where(['end_adminid'=>$this->admin->id,'status'=>['in',[1,2,3,4]],'overtype'=>0])->count();
        $data['warnCheck'] = bcadd($check->where(['end_adminid'=>$this->admin->id,'status'=>['in',[1,2,3,4]],'type'=>1,'san_check|look_check|low_check|obd_check|huan_check|an_check'=>2])->count(),
            $check->where(['end_adminid'=>$this->admin->id,'status'=>['in',[1,2,3,4]],'type'=>2,'san_check'=>2])->count(),0);
        $this->success($this->successMsg,$data);
    }

    /**
     * @return void
     * 订单列表
     */
    public function orderList()
    {
        $this->requireAdminLogin();
        $type = $this->request->get('type',0);//0=报废订单,1=检测订单
        $model = $type == 0 ? new Order() : new Orders();
        $where['end_adminid'] = $this->admin->id;
        $status = $this->request->get('status','normal');
        //开始数据组装
        if($type == 0){
            //报废订单
            switch ($status){
                case 'normal':
                    $where['status'] = ['in',[1,2,3]];
                    break;
                case 'over':
                    $where['status'] = 4;
                    break;
                case 'warn':
                    $where['status'] = ['in',[1,2,3,4]];
                    $where['overtype'] = 0;
                    break;
            }
        }else{
            //检测订单
            switch ($status){
                case 'normal':
                    $where['status'] = ['in',[1,2,3]];
                    break;
                case 'over':
                    $where['status'] = 4;
                    break;
                case 'warn':
                    $where['status'] = ['in',[1,2,3,4]];
                    $where['san_check|look_check|low_check|obd_check|huan_check|an_check'] = 2;
                    break;
            }
        }
        $this->success($this->successMsg,$model->where($where)->order(['id'=>'desc'])->paginate());
    }

    /**
     * @return void
     * 订单详情
     */
    public function orderDetail()
    {
        $this->requireAdminLogin();
        $type = $this->request->get('type',0);//0=报废订单,1=检测订单
        $order_id = $this->request->get('order_id',0);
        $model = $type == 0 ? new Order() : new Orders();
        $data = $model->where(['end_adminid'=>$this->admin->id,'id'=>$order_id])->find();
        if($type == 0)
            $data['end_json'] = json_decode($data['end_json']);
        $this->success($this->successMsg,$data);
    }

    /**
     * 开始检测--检测订单
     */
    public function checkBegin()
    {
        $this->requireAdminLogin();
        $ids = $this->request->param('id');
        //检测订单model初始化
        $model = new Orders();
        $data = $model->find($ids);
        if($data->status == 0)
            $this->error('订单未支付');
        if($data->end_adminid != $this->admin->id)
            $this->error('暂无权限');
        if($data->status > 1)
            $this->error('检测已开始');
        $data->status = 2;
        $data->begintime = time();
        $data->save();
        $this->success('操作成功');
    }
    /**
     * 检测录入--检测订单
     */
    public function checkEdit()
    {
        $ids = $this->request->param('id');
        //检测订单model初始化
        $model = new Orders();
        $row = $model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->status < 2)
            $this->error('请先开始检测');
        if($row->status > 2)
            $this->error('检测已结束');
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        //如果填写了验车结束时间，自动结束验车
        if($params['overtime'])
        {
            if(strtotime($params['overtime']) <= $row->begintime)
                $this->error('结束时间不合法');
            if($row->type == 1 && ($params['look_check'] == 0 || $params['low_check'] == 0 || $params['obd_check'] == 0 || $params['huan_check'] == 0 || $params['an_check'] == 0 || $params['san_check'] == 0))
                $this->error('存在检测中的检测项');
            if($row->type == 2 && $params['san_check'] == 0)
                $this->error('请先完成三电检测');
            $params['status'] = 3;
        }
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            if($row->status == 3)
            {
                //给检测厂返利
                User::money($row->end_price,db('admin')->where(['id'=>$row->end_adminid])->value('userid'),'检测订单'.$row->numbers.'收益到账');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 检测结果上传--回收订单
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function backEdit()
    {
        $ids = $this->request->param('id');
        //检测订单model初始化
        $model = new Order();
        $row = $model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        if(!isset($params['is_diving']) && $row->status <= 1)
            $this->error('请先开始验车');
        if(!isset($params['is_diving']))
        {
            //如果填写了验车结束时间，自动结束验车
            if($params['endtime'])
            {
                if(strtotime($params['endtime']) <= $row->begintime)
                    $this->error('结束时间不合法');
                $params['status'] = 3;
            }
            $params['end_price'] = !$params['end_price'] ? $row->end_price : $row->end_price+$params['end_price'];
        }else{
            if($params['is_diving'] != $row->is_diving)
            {
                $temp = [0,$row->estimated_amount,$row->tuoche_amount,0];
                $params['end_price'] = bcadd(bcsub($row->end_price,$temp[$row->is_diving],2),$temp[$params['is_diving']],2);
            }
        }
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 开始验车--回收订单
     */
    public function backBegin()
    {
        $ids = $this->request->param('id');
        //检测订单model初始化
        $model = new Order();
        $data = $model->find($ids);
        if($data->end_status != 2)
            $this->error('请等待打款确认');
        if($data->status > 1)
            $this->error('检测已开始');
        $data->status = 2;
        $data->begintime = time();
        $data->save();
        $this->success('操作成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 打款--回收订单
     */
    public function backPayment()
    {
        $ids = $this->request->param('id');
        //检测订单model初始化
        $model = new Order();
        $data = $model->find($ids);
        if($data->status == 0)
            $this->error('请先确认合作');
        if($data->end_status != 0)
            $this->error('已打款，请勿重复操作');
        $data->end_status = 1;
        $data->payment_time = time();
        $data->save();
        $this->success('打款成功');
    }
}